package zhongbo.java.air.common.web;

import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import zhongbo.java.air.common.util.HttpServletUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * 请求过滤器, 打印请求日志
 *
 * @author dbSven
 * @implNote
 * @since 2020/8/11 10:30
 */
@Component
@Slf4j
public class ControllerFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String ip = ServletUtil.getClientIP(request, "x-forwoarded-for");
        String name = HttpServletUtil.getUserNameFromToken();
        Date startTime = new Date();
        log.info("【" + ip + "】" + "【" + request.getMethod() + "】【" + name + "】调用" + request.getRequestURI());
        filterChain.doFilter(servletRequest, servletResponse);
        Date endTime = new Date();
        log.info("【" + ip + "】" + "【" + request.getMethod() + "】【" + name + "】调用" + request.getRequestURI() + "时间:" + (endTime.getTime() - startTime.getTime()) + "ms");
    }

    @Override
    public void destroy() {

    }
}
